﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Keepo.Models;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
using Keepo.Models.Services;

namespace Keepo.Helpers
{
    public class FacebookHelper
    {
        const string myTagsAlbumId = "myTagsAlbumId";

        public static bool isConnected()
        {
            dynamic permissionsData = GetDataFromFacebook("https://graph.facebook.com/me/permissions/");
            if (permissionsData != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        public static dynamic GetDataFromFacebook(string graphUrl)
        {
            var accessToken = HttpContext.Current.Session["accessToken"];

            if (accessToken != null)
            {
                //read the Facebook Photos into JSON string
                WebRequest wr = WebRequest.Create(graphUrl + "?access_token=" + accessToken);
                var response = wr.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string photosJSONstr = reader.ReadToEnd();

                //Deserialize the JSON string to Photos .net Dynamic Variable
                JavaScriptSerializer js = new JavaScriptSerializer();
                
                //Dictionary<string, object>
                Dictionary<string, object> result = (js.DeserializeObject(photosJSONstr) as Dictionary<string, object>);

                Dictionary<string, object> finalResult = result;

                if (result.ContainsKey("error"))
                {
                    return null;
                }

                if (result.ContainsKey("data"))
                {
                    while (result.ContainsKey("paging"))
                    {
                        var dic = result["paging"] as  Dictionary<string, object>;

                        if (dic.ContainsKey("next"))
                        {
                            var url = dic["next"].ToString();
                            wr = WebRequest.Create(url);
                            response = wr.GetResponse();
                            reader = new StreamReader(response.GetResponseStream());
                            photosJSONstr = reader.ReadToEnd();
                            result = (js.DeserializeObject(photosJSONstr) as Dictionary<string, object>);

                            if ((result["data"] as object[]).Length > 0)
                            {
                                finalResult["data"] = (finalResult["data"] as object[]).Concat(result["data"] as object[]).ToArray();
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                //dynamic albumsData = photosObj["data"];

                return finalResult;
            }
            else
            {
                return null;
            }

        }

        public static DesignImage ImportImageFromFacebook(long facebookImageId)
        {
            string graphUrl = "https://graph.facebook.com/" + facebookImageId.ToString() + "/";

            dynamic imageData = GetDataFromFacebook(graphUrl);

            if (imageData != null)
            {
                DesignImage image = new DesignImage();
                image.ExternalId = facebookImageId;
                image.ImageCategoryId = 1;
                image.Title = imageData["from"]["name"];

                string filname = Path.GetFileName(imageData["source"]);
                var relativePath = Path.Combine("resources/img/", filname);
                var rootedPath = HttpContext.Current.Server.MapPath(Path.Combine("~/", relativePath));
                image.URL = relativePath;

                byte[] data;
                using (WebClient client = new WebClient())
                {
                    data = client.DownloadData(imageData["source"]);
                }

                try
                {
                    File.WriteAllBytes(rootedPath, data);
                }
                catch { return null; }

                ImageHelper.addDesignImage(image);

                return image;
            }

            return null;
        }


        public static DesignImageExport[] GetPhotosByAlbumId(string albumId)
        {
            string graphUrl = "";

            switch (albumId)
            {
                case myTagsAlbumId:
                    graphUrl = "https://graph.facebook.com/me/photos/";
                    break;

                default:
                    graphUrl = "https://graph.facebook.com/" + albumId.ToString() + "/photos/";
                    break;
            }

            dynamic photosData = GetDataFromFacebook(graphUrl);

            if (photosData != null)
            {
                List<DesignImageExport> photos = new List<DesignImageExport>();

                foreach (var photo in photosData["data"])
                {
                    DesignImageExport image = new DesignImageExport();
                    image.ThumbnailURL = photo["picture"];
                    image.URL = photo["source"];
                    image.ExternalImageId = photo["id"];

                    try
                    {
                        image.Title = photo["name"];
                    }
                    catch { }

                    photos.Add(image);
                }

                return photos.ToArray();
            }
            else
            {
                return null;
            }

        }

        static public Dictionary<string, object> createMyTagsAlbum()
        {
            Dictionary<string, object> album = new Dictionary<string, object>();

            album["key"] = myTagsAlbumId;
            album["english"] = "My Tags";
            album["hebrew"] = "תמונות שאני מתוייג בהן";

            return album;
        }

        public static Dictionary<string, object>[] GetAlbumsFromFacebook()
        {
            dynamic albumsData = GetDataFromFacebook("https://graph.facebook.com/me/albums/");

            if (albumsData != null)
            {
                List<Dictionary<string, object>> albums = new List<Dictionary<string, object>>();
                List<string> uniqs = new List<string>();

                albums.Add(createMyTagsAlbum());

                //insert all photos to the "DesignImageExport" List
                foreach (var albumData in albumsData["data"])
                {
                    Dictionary<string, object> album = new Dictionary<string, object>();

                    album["key"] = albumData["id"];
                    album["english"] = albumData["name"];
                    album["hebrew"] = albumData["name"];

                    if(!uniqs.Contains(albumData["id"]))
                    {
                        uniqs.Add(albumData["id"]);
                        albums.Add(album);
                    }
                }

                return albums.ToArray();
            }
            else
            {
                return null;
            }

        }
    }
}